/*** 
 * @_______________#########_______________________ 
 * @______________############_____________________ 
 * @______________#############____________________ 
 * @_____________##__###########___________________ 
 * @____________###__######_#####__________________ 
 * @____________###_#######___####_________________ 
 * @___________###__##########_####________________ 
 * @__________####__###########_####_______________ 
 * @________#####___###########__#####_____________ 
 * @_______######___###_########___#####___________ 
 * @_______#####___###___########___######_________ 
 * @______######___###__###########___######_______ 
 * @_____######___####_##############__######______ 
 * @____#######__#####################_#######_____ 
 * @____#######__##############################____ 
 * @___#######__######_#################_#######___ 
 * @___#######__######_######_#########___######___ 
 * @___#######____##__######___######_____######___ 
 * @___#######________######____#####_____#####____ 
 * @____######________#####_____#####_____####_____ 
 * @_____#####________####______#####_____###______ 
 * @______#####______;###________###______#________ 
 * @________##_______####________####______________ 
 * @
 * @Author: ipk518 18163976442@163.com
 * @Date: 2024-06-19 10:31:14
 * @LastEditors: ipk518 121206530@qq.com
 * @LastEditTime: 2025-10-18 10:57:14
 * @FilePath: /etws-sxk2307/src/Service/Hardware.cpp
 * @Description: 
 * @************佛祖保佑************
 * @Copyright (c) 2024 by etws@quyujiang, All Rights Reserved. 
 */



#include "Hardware.h"
#include "commHeader.h"
#include "Mem.h"
#include "getConfig.h"

#include "servoMotor.h"
#include "Uio.h"
#include "Lmx2820.h"
#include "Ad9171.h"
#include "Hmc7044.h"
#include "Ina3221.h"
#include "Si5341.h"
#include "Gpio.h"
#include "sht35.h"
#include "Qsfp.h"
#include "gnss.h"

#define RUNNING_ILLEGAL(param, min, max) \
    if ((param >= min && param <= max)) { \
        qlog_e("雷达正在运行，这个地址:%#x 目前处于写保护中",param); \
        return -1; \
    }

#define POWER_ON    0
#define POWER_OFF   1

#define _Debug_t_
/**
 * @brief: 时序卡硬件初始化
 * @return {*}
 */
bool Hardware::Init()
{
    
    Xil_In32(TIMING_CONFIG_BASEADDR,0x00060002);
    memFd = openMem();
    if(memFd < 0) {
        qlog_e("Hardware openMem failed.");
        return false;
    }
    
    gpioInit();
    
    plVersion();
    psVersion();
    //TODO：2025/10/14 ，先拉死PL复位，等待时钟初始化
    setGpioValue(Conf::currentConf()->mGpioConf.uPlReset,0); //先拉死PL复位，等待时钟初始化
#ifdef _Debug_t_
    if ( hmc7044Open(HMC7044_DEV_NAME) ) {
        qlog_i("HMC7044设备打开成功。");
        hmc7044GetStatus(m_sxkInfo.m_hmc7044);
    } else {
        return false;
    }
    
    if ( lmx2820Open(Conf::currentConf()->mParam.uLmx2820Dev.c_str())) {
        qlog_i("lmx2820设备打开成功。");
        lmx2820Config();
    } else {
        return false;
    }

    (void)system("sudo i2ctransfer -f -y 0 w2@0x70 0x00 0xff");
    // system("sudo i2ctransfer -f -y 0 w2@0x50 0x01 0x00");
    if ( si5341Open(SI5341_DEV_NAME) ) {
        qlog_i("SI5341设备打开成功。");
        si5341Config();
        si5341GetStatus(m_sxkInfo.m_si5341);
    } else {
        return false;
    }

    if ( qsfp_4x_init() ) {
        qlog_i("QSFP设备打开成功。");
        if(qsfp_4x_check() == 1) {
            qsfp_power();
        } else {
            // return false;
        }
    } else {
        // return false;
    }
      
    {
        int nCo = 0;
        int m_lmxLock = 0,m_hmc7044Lock = 0;
        while(1) {
            m_lmxLock = lmx2820GetLock();
            m_hmc7044Lock = hmc7044GetLock();
            qlog_w("等待LMX2820:%s,HMC7044:%s,时钟锁定检测中..",
            (m_lmxLock == 2)?"锁定":"未锁定",
            (m_hmc7044Lock == 1)?"锁定":"未锁定");
            
            if(m_lmxLock == 2 && m_hmc7044Lock == 1){
                qlog_i("时钟已锁定..");
                nCo = 0;
                break;
            } else {
                nCo++;
            }

            if(nCo > 24) { //最多初始化2次
                qlog_e("初始化流程退出,时钟未锁定,请手动复位..");
                break;
            }

            if(nCo%12 == 0) {
                if (m_hmc7044Lock != 1) {
                    qlog_w("初始化流程,复位HMC7044设备..");
                    hmc7044Reset();
                    sleep(5);
                }
                
                if(m_lmxLock != 2) {
                    qlog_w("初始化流程,复位lmx2820设备..");
                    if (lmx2820Reset()) {
                        sleep(3);
                        lmx2820Config();
                    }
                    sleep(3);
                    
                }
            }
            sleep(1);
        }
    }
    plReset();//TODO：2024-11-28
    initPlRfSync();
    if ( ad9171Open(Conf::currentConf()->mParam.uAd9171Dev.c_str()) ) {
        qlog_i("AD9171设备打开成功。");
        ad9171Config();
    } else {
        return false;
    }

    qlog_w("ad9171 check=%#x",ad9171Check());
#endif


    qlog_i("初始化伺服控制...");
	m_servo = new servoMotor();
    m_mtUart = new uartLite(1000);
    if(m_mtUart != nullptr) {
        m_mtUart->Init(SERVO_NAME,115200);
        isRunning = true;
    }
    servoFd = new std::thread(std::bind(&Hardware::servoProtocolTask,this));
    
    qlog_i("初始化GNSS控制...");
    m_gnssUart  = new gnss();
    if(m_gnssUart != nullptr) {
        m_gnssUart->Init(GNSS_NAME);
    }

    m_uio = new Uio();
    if(false == m_uio->Init()) { //硬件检测未通过，关闭正常运行
        return false;
    }

    hwInit();
    hwHandle(m_sxkInfo.m_sxkParam);
    
    m_isInit = true;
    qlog_i("SXK hardware initialized sucess...");
    return true;
}

void Hardware::deInit()
{
    m_isInit = false;
    qlog_i("sxkHardware deInit...");
    if (m_servo != nullptr) {
        delete m_servo;
        m_servo = nullptr;
    }
    if (memFd >= 0) {
        close(memFd);
        memFd = -1;
    }
    if (servoFd != nullptr) {
        servoFd->join();
        delete servoFd;
        servoFd = nullptr;

        delete m_mtUart;
    }
    if (m_uio != nullptr) {
        delete m_uio;
        m_uio = nullptr;
    }
    hmc7044Close();
    ad9171Close();
    lmx2820Close();
    si5341Close();
    qsfpClose();
    // dataRelese();
}
  
/**
 * @brief: 获取硬件状态参数,每500ms进入一次
 * @return {*}
 */
void Hardware::run()
{
    
    if (m_isInit) {
        updateDate();
        process_1000ms();
        process_1500ms();
        process_2000ms();
        process_3000ms();
        process_5000ms();
        
    } else {
        qlog_e("SXK hardware not init ");
    }

}

/*** 
 * @description: 设置GPS时间，用于日志更新
 * @return {*}
 */
void Hardware::updateDate()
{
    static bool isUpdated = false;
    if (isUpdated) {
        return;
    }

    // 检查是否有有效的UTC数据
    if (m_sxkInfo.m_gnssUpdateRtu.utc_data[0] == 0) {
        return;
    }

    // 解析两位数字的辅助函数
    auto parseTwoDigitNumber = [](uint16_t utf16_value, int& result) -> bool {
        uint8_t low_byte = utf16_value & 0xFF;   // 低位字节 (个位)
        uint8_t high_byte = (utf16_value >> 8) & 0xFF;  // 高位字节 (十位)
        
        // 验证是否为数字字符
        if (low_byte < '0' || low_byte > '9' || high_byte < '0' || high_byte > '9') {
            return false;
        }
        
        int tens = low_byte - '0';
        int units = high_byte - '0';
        result = tens * 10 + units;
        return true;
    };

    // 解析日期
    int day, month, year;
    if (!parseTwoDigitNumber(m_sxkInfo.m_gnssUpdateRtu.utc_data[0], day) ||
        !parseTwoDigitNumber(m_sxkInfo.m_gnssUpdateRtu.utc_data[1], month) ||
        !parseTwoDigitNumber(m_sxkInfo.m_gnssUpdateRtu.utc_data[2], year)) {
        qlog_e("GNSS日期解析失败");
        return;
    }

    // 年份转换为4位 (假设2000-2099范围)
    int full_year = year + 2000;

    // 解析时间 hhmmss.sss
    int hour = 0, minute = 0, second = 0;
    if (m_sxkInfo.m_gnssUpdateRtu.utc_time[0] != 0) {
        int parsed_hour, parsed_minute, parsed_second;
        if (parseTwoDigitNumber(m_sxkInfo.m_gnssUpdateRtu.utc_time[0], parsed_hour) &&
            parseTwoDigitNumber(m_sxkInfo.m_gnssUpdateRtu.utc_time[1], parsed_minute) &&
            parseTwoDigitNumber(m_sxkInfo.m_gnssUpdateRtu.utc_time[2], parsed_second)) {
            hour = parsed_hour + 8;
            minute = parsed_minute;
            second = parsed_second;
        }
    }

    qlog_i("解析GNSS时间: %04d年%02d月%02d日 %02d:%02d:%02d", 
           full_year, month, day, hour, minute, second);

    // 验证数据合理性
    if (full_year < 2020 ||
        month < 1 || month > 12 ||
        day < 1 || day > 31 ||
        hour < 0 || hour > 23 ||
        minute < 0 || minute > 59 ||
        second < 0 || second > 59) {
        qlog_e("GNSS时间数据不合理");
        return;
    }

    // 设置系统时间
    char dateString[32];
    snprintf(dateString, sizeof(dateString), "%04d-%02d-%02d %02d:%02d:%02d",
             full_year, month, day, hour, minute, second);

    std::string cmd = "date -s \"" + std::string(dateString) + "\"";
    qlog_i("设置系统时间: %s", cmd.c_str());

    int ret = system(cmd.c_str());
    if (ret != 0) {
        qlog_e("时间配置失败，返回码: %d", ret);
        return;
    }

    // 同步硬件时钟到系统时钟
    ret = system("hwclock -w");
    if (ret != 0) {
        qlog_w("硬件时钟同步失败，返回码: %d", ret);
    }

    qlog_i("系统时间设置成功");
    isUpdated = true;
}

/*** 
 * @description: AD同步
 * @return {*}
 */
void Hardware::initADSync()
{
    qlog_w("执行AD同步.");
    setGpioValue(Conf::currentConf()->mGpioConf.uPlAdSync,1);
    usleep(1000);
    setGpioValue(Conf::currentConf()->mGpioConf.uPlAdSync,0);
    usleep(1000);
}


/*** 
 * @description: 获取PL版本
 * @return {*}
 */
void Hardware::plVersion()
{
    int len = 14*4;//保证8n个字节
    unsigned long addr = PL_VERSION_BASEADDR;
    memorySwap(memFd,addr,m_read,len,nullptr,0);
    memcpy(&m_sxkInfo.m_plVersion,m_read,sizeof(struct PlVerisonInfo));
    qlog_i("PL priCode:%x",m_sxkInfo.m_plVersion.m_priCode);
    qlog_i("PL Version: V%dR%d",m_sxkInfo.m_plVersion.m_prjVersion,m_sxkInfo.m_plVersion.m_prjMinVersion);
    qlog_i("PL date:%x-%x",m_sxkInfo.m_plVersion.m_dateDay,m_sxkInfo.m_plVersion.m_dateTime);
}

/*** 
 * @description: 获取PS版本
 * @return {*}
 */
void Hardware::psVersion()
{
    m_sxkInfo.m_psVersion.m_year = 0x2025;
    m_sxkInfo.m_psVersion.m_month = buildMonth();
    m_sxkInfo.m_psVersion.m_data = buildDay();
    m_sxkInfo.m_psVersion.m_major = majorVersion();
    m_sxkInfo.m_psVersion.m_minor = minorVersion();
    m_sxkInfo.m_psVersion.m_patch = patchVersion();
    qlog_i("PS Version: V%d.%d.%d..", m_sxkInfo.m_psVersion.m_major, m_sxkInfo.m_psVersion.m_minor, m_sxkInfo.m_psVersion.m_patch);
    qlog_i("PS Date: %d-%d-%d", m_sxkInfo.m_psVersion.m_year, m_sxkInfo.m_psVersion.m_month, m_sxkInfo.m_psVersion.m_data);
}

/**
 * @brief: 电源控制
 * @param {bool} enabled
 * @param {int} powerType 0：代表全选
 * @param {int} powerNum 0：代表全选
 * @return {*}
 */
void Hardware::powerControl(bool enabled,int powerType,int powerNum)
{
    if (!m_isInit) return;

	if(powerType == 0 && powerNum == 0) {//全控制
        setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp0,(enabled == true)?POWER_ON:POWER_OFF);
        setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp1,(enabled == true)?POWER_ON:POWER_OFF);
        setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp2,(enabled == true)?POWER_ON:POWER_OFF);
        setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp3,(enabled == true)?POWER_ON:POWER_OFF);
        setGpioValue(Conf::currentConf()->mGpioConf.uPowerPz,(enabled == true)?POWER_ON:POWER_OFF);
        qlog_i("执行电源全控:%s",(enabled == true)?"打开所有组件电源.":"关闭所有组件电源.");
	} else { //分组控制
        if(powerType == 1) { //TR
            switch(powerNum)
            {
                case 0:
                    setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp0,(enabled == true)?POWER_ON:POWER_OFF);
                    setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp1,(enabled == true)?POWER_ON:POWER_OFF);
                    qlog_i("执行TR组件电源全控:%s",(enabled == true)?"打开TR组件电源.":"关闭TR0组件电源.");
                break;
                case 1:
                    setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp0,(enabled == true)?POWER_ON:POWER_OFF);
                    if (enabled == true) { qlog_i("打开TR0组件电源."); }else {qlog_i("关闭TR0组件电源.");}
                break;
                case 2:
                    setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp1,(enabled == true)?POWER_ON:POWER_OFF);
                    if (enabled == true) { qlog_i("打开TR1组件电源."); }else {qlog_i("关闭TR1组件电源.");}
                break;
            }
        }

        if(powerType == 2) { //AD
            switch(powerNum)
            {
                case 0:
                    setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp2,(enabled == true)?POWER_ON:POWER_OFF);
                    setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp3,(enabled == true)?POWER_ON:POWER_OFF);
                    qlog_i("执行AD组件电源全控.");
                break;
                case 1:
                    setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp2,(enabled == true)?POWER_ON:POWER_OFF);
                    if (enabled == true) { qlog_i("打开AD0组件电源."); }else {qlog_i("关闭AD0组件电源.");}
                break;
                case 2:
                    setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp3,(enabled == true)?POWER_ON:POWER_OFF);
                    if (enabled == true) { qlog_i("打开AD1组件电源."); }else {qlog_i("关闭AD1组件电源.");}
                break;
            }
        }

        if (powerType == 3) { //PZ
            setGpioValue(Conf::currentConf()->mGpioConf.uPowerPz,(enabled == true)?POWER_ON:POWER_OFF);
            if (enabled == true) { qlog_i("打开PZ组件电源."); }else {qlog_i("关闭PZ组件电源.");}
        }
	}
}

/*** 
 * @description: 时钟状态锁定监测
 * @return {*}
 */
bool Hardware::checkClockLockStatus()
{
    int m_lmxLock = 0 ,m_hmc7044Lock = 0;
    m_lmxLock = lmx2820GetLock();
    m_hmc7044Lock = hmc7044GetLock();
    if(m_hmc7044Lock != 1 || m_lmxLock != 2) {
        qlog_e("时钟错误,无法正常工作,请手动复位时钟.LMX2820:%s,HMC7044:%s,时钟锁定..",(m_lmxLock == 2)?"锁定":"未锁定",
            (m_hmc7044Lock == 1)?"锁定":"未锁定");
        return false;
    }
    return true;
    
}
/**
 * @brief: 数据初始化
 * @return {*}
 */
void Hardware::dataInit()
{   
    
    memset(m_read,0,sizeof(m_read));
    memset(m_write,0,sizeof(m_write));
    memset(m_rxAutoCaliCoe,0,sizeof(m_rxAutoCaliCoe));
    memset(m_rxManualCaliCoe,0,sizeof(m_rxAutoCaliCoe));
    memset(m_readRxDbfCoff,0,sizeof(m_readRxDbfCoff));
    memset(readBeamList,0,sizeof(readBeamList));
    memset(trChannelStatus,0,sizeof(trChannelStatus));
    memset(m_rxDbfPoint,-1800,sizeof(m_rxDbfPoint));
    memset(m_phaseCode,0,sizeof(m_phaseCode));
    memset((uint8_t *)&m_sxkHardTest,0,sizeof(m_sxkHardTest));

    //相位码
    m_phaseWriteNum = Conf::currentConf()->mPhaseConf.uWriteNum;
    memcpy(m_phaseCode[0],Conf::currentConf()->mPhaseConf.uPhaseCode,sizeof(uint16_t)*32);
    memcpy(m_phaseCode[1],Conf::currentConf()->mPhaseConf.uPhaseCode,sizeof(uint16_t)*32);
    memcpy(m_phaseCode[2],Conf::currentConf()->mPhaseConf.uPhaseCode,sizeof(uint16_t)*32);
    memcpy(m_phaseCode[3],Conf::currentConf()->mPhaseConf.uPhaseCode,sizeof(uint16_t)*32);
    //BEAM0-BEAM31
    for(int i=0; i<32; i++) {
        memcpy(beamParamReg[i],Conf::currentConf()->mBeamConf.uBeamPara,sizeof(uint16_t)*130);
    }
    //发射H校准参数
    memcpy(beamParamReg[32],Conf::currentConf()->mBeamConf.uTxBeamPara,sizeof(uint16_t)*130);
    //发射V校准参数
    memcpy(beamParamReg[33],Conf::currentConf()->mBeamConf.uTxBeamPara,sizeof(uint16_t)*130);
    //接收H校准参数
    memcpy(beamParamReg[34],Conf::currentConf()->mBeamConf.uRxBeamPara,sizeof(uint16_t)*130);
    //接收V校准参数
    memcpy(beamParamReg[35],Conf::currentConf()->mBeamConf.uRxBeamPara,sizeof(uint16_t)*130);

    //波位调度表
    memcpy(beamList,Conf::currentConf()->mBeamConf.uBeamList,sizeof(uint8_t)*36);

    m_radarSendFreq = 0;
    for(int i=0; i< 512; i++) {
        for(int j=0; j<32;j++) {
            m_rxDbfCoff[i].m_chlCoefIQ[j][0] = 0x7FFF;
            m_rxDbfCoff[i].m_chlCoefIQ[j][1] = 0;
        }
    }
    for(int i=0;i<32;i++) {
        m_rxManualCaliCoe[i].m_h_i0Buffer = 0x3FFF;
        m_rxManualCaliCoe[i].m_h_q0Buffer = 0;
        m_rxManualCaliCoe[i].m_h_i1Buffer = 0x3FFF;
        m_rxManualCaliCoe[i].m_h_q1Buffer = 0;
        m_rxManualCaliCoe[i].m_v_i0Buffer = 0x3FFF;
        m_rxManualCaliCoe[i].m_v_q0Buffer = 0;
        m_rxManualCaliCoe[i].m_v_i1Buffer = 0x3FFF;
        m_rxManualCaliCoe[i].m_v_q1Buffer = 0;
    }
    memcpy(m_rxAutoCaliCoe,m_rxManualCaliCoe,sizeof(m_rxAutoCaliCoe));

    //TODO:2024-11-19
    m_sxkHardTest.minfreq_0 = 387000 - 360000; //27000
    m_sxkHardTest.minfreq_1 = 393000 - 360000; //33000
    m_sxkHardTest.WaveWidth = 4000;
    m_sxkHardTest.dac_am_strength = 2000;
    m_sxkHardTest.dac_fm_strength = 2000;
    m_sxkHardTest.internal_cnt_hold = 1;
    //TODO:2025-3-24
    m_sxkHardTest.tr_receive_switch = 0x03;//默认开启接收开关
    // m_sxkHardTest.tr0_send_switch = 0xffff;//0-15通道
    // m_sxkHardTest.tr1_send_switch = 0xffff;//0-15通道bit

    m_sxkHardTest.interrput_change = 0; //TODO:2025-0804 0:外部触发 1:内部触发
    m_sysConfig.AutoCalibrationEN = 0;
    m_sysConfig.AutoCalibrationTime = 600;

    m_datktsConf.m_debug = 
    Conf::currentConf()->mTestConf.uDarktsEnable;   //打印 0:关闭 1:打开日志

    setHardwareTestPara();//数据初始化

    qlog_i("数据初始化完成.");
    
}

/*** 
 * @description: GPIO控电，测试流程中默认在线
 * @return {*}
 */
void Hardware::gpioInit()
{
    int ret = 0;
    ret = initGpio(Conf::currentConf()->mGpioConf.uPowerUp0,"out");
    if (ret == 0) {
        setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp0,POWER_OFF);
    }
    ret = initGpio(Conf::currentConf()->mGpioConf.uPowerUp1,"out");
    if (ret == 0) {
        setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp1,POWER_OFF);
    }
    ret = initGpio(Conf::currentConf()->mGpioConf.uPowerUp2,"out");
    if (ret == 0) {
        setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp2,POWER_OFF);
    }
    ret = initGpio(Conf::currentConf()->mGpioConf.uPowerUp3,"out");
    if (ret == 0) {
        setGpioValue(Conf::currentConf()->mGpioConf.uPowerUp3,POWER_OFF);
    }
    ret = initGpio(Conf::currentConf()->mGpioConf.uPowerPz,"out");
    if (ret == 0) {
        setGpioValue(Conf::currentConf()->mGpioConf.uPowerPz,POWER_ON);
    }
    initGpio(Conf::currentConf()->mGpioConf.uAd9171nRST,"out");
    initGpio(Conf::currentConf()->mGpioConf.uAd9171TxEn0,"out");
    initGpio(Conf::currentConf()->mGpioConf.uAd9171TxEn1,"out");
    //锁定脚
    initGpio(Conf::currentConf()->mGpioConf.uPlPllStatus,"in");
    //同步PL
    initGpio(Conf::currentConf()->mGpioConf.uPlRfSync,"out");
    setGpioValue(Conf::currentConf()->mGpioConf.uPlRfSync,0);
    //自动校准
    initGpio(Conf::currentConf()->mGpioConf.uPlAutoAlign,"out");
    //AD同步信号
    initGpio(Conf::currentConf()->mGpioConf.uPlAdSync,"out");
    setGpioValue(Conf::currentConf()->mGpioConf.uPlAdSync,0);
    //复位GPIO
    // initGpio(Conf::currentConf()->mGpioConf.uPlReset,"out");
    // setGpioValue(Conf::currentConf()->mGpioConf.uPlReset,1);
    
}

/*** 
 * @description: 初始化同步RF
 * @return {*}
 */
bool Hardware::initPlRfSync()
{
    qlog_w("执行PL部分的RF同步..");
    setGpioValue(Conf::currentConf()->mGpioConf.uPlRfSync,1);
    usleep(100);
    setGpioValue(Conf::currentConf()->mGpioConf.uPlRfSync,0);
    usleep(100);
    return true;
}

/*** 
 * @description: 开启暗室配置
 * @param {bool} ret
 * @return {*}
 */
void Hardware::darktsSwitch(bool ret)
{
    uint32_t val=0;
    uint8_t m_reg[4];
    hardwareSync();
    if (ret == true) {
        qlog_i("执行PL部分的暗室开启..");
        //开启暗室中断触发
        m_sxkHardTest.interrput_enable = 1;
        setHardwareTestPara();
        m_controlReg.m_timingStatus = TIME_START;//产生正常时序
        setSysTimingPara();
        m_uio->u_DarktsComplete = false;//清除暗室数据完整标志位
    } else {
        qlog_i("执行PL部分的暗室停止..");
        qlog_i("延时2s..");
        sleep(2);
        //停止暗室中断触发
        m_sxkHardTest.interrput_enable = 0;
        setHardwareTestPara();
        m_controlReg.m_timingStatus = TIME_STOP;//关闭时序
        setSysTimingPara();
        //配置暗室脉冲计数清零
        val = Xil_Out32(TIMING_CONFIG_BASEADDR+136);
        memcpy(m_reg,(uint8_t *)&val,4);
        m_sxkHardTest.interrput_rst = 0;
        m_reg[3] = 0;
        Xil_In32(TIMING_CONFIG_BASEADDR+136,*(uint32_t *)m_reg);
        m_sxkHardTest.interrput_rst = 1;
        m_reg[3] = 1;
        Xil_In32(TIMING_CONFIG_BASEADDR+136,*(uint32_t *)m_reg);
        m_sxkHardTest.interrput_rst = 0;
        m_reg[3] = 0;
        Xil_In32(TIMING_CONFIG_BASEADDR+136,*(uint32_t *)m_reg);
        //配置暗室脉冲计数清零
        m_uio->isPackage = true;//打包上报
        sem_post(&m_uio->g_packageTask);
    }
    
}

/**
 * @brief: 雷达系统服务复位
 * @return {*}
 */
bool Hardware::plReset()
{
    bool ret = (getGpioValue(Conf::currentConf()->mGpioConf.uPlPllStatus) == 1)?true:false;
    if(ret) {
        m_resetCount++;
        qlog_w("执行PL系统复位=%d..",m_resetCount);
        sysRunStatus = SYS_INIT;
        setGpioValue(Conf::currentConf()->mGpioConf.uPlReset,1);
        sleep(1);
        setGpioValue(Conf::currentConf()->mGpioConf.uPlReset,0); //0复位
        sleep(1);
        setGpioValue(Conf::currentConf()->mGpioConf.uPlReset,1);
        sleep(1);
        sysRunStatus = SYS_RUN;
    }
    
	return ret;
}

bool Hardware::psReset()
{
    if (!getLockStatus()) return false;
	m_resetCount++;
    qlog_w("执行PS系统复位=%d..",m_resetCount);
	sysRunStatus = SYS_INIT;
	sleep(1);
	sysRunStatus = SYS_RUN;
    resetInit(m_hmc7044);
    resetInit(m_lmx2820);
    resetInit(m_ad9171);
    resetInit(m_timingParam);
    resetInit(m_dbf);
    resetInit(m_beamList);
    
	return true;
}

void Hardware::getLVDSStatus()
{
    int len = sizeof(struct SxkLvdsError);//保证8n个字节
    unsigned long addr = AXIREG_LVDS_ERROR_BASEADDR;
    memorySwap(memFd,addr,m_read,len,nullptr,0);
    memcpy((uint8_t *)&m_sxkInfo.m_lvdsError,m_read,len);
    if ( (m_sxkInfo.m_lvdsError.e_hsi_status & 0x0f) != 0x0f) {
        qlog_e("ADC训练错误,错误值:%x",(m_sxkInfo.m_lvdsError.e_hsi_status)&0x0f);
    }
}

/**
 * @brief: 实时监测，锁定失败则关闭硬件相关功能
 * @return {*}
 */
bool Hardware::getLockStatus()
{
    if (!m_isInit) return false;

    bool ret = (getGpioValue(Conf::currentConf()->mGpioConf.uPlPllStatus) == 1)?true:false;
    if (false == ret) {
        qlog_e("pl系统状态未锁定,无法操作内存..");
        m_sxkInfo.m_status.m_timingLock = 0;
    } else {
        m_sxkInfo.m_status.m_timingLock = 1;
    }
    
    return ret;
}


int Hardware::plRead(struct memoryOperation& memOp)
{
    if (!getLockStatus()) return -1;

    int ret = 0;
    qlog_n("读PL地址:%#x! ",memOp.m_addr);
    qlog_n("读PL地址长度:%d.!",memOp.m_len);
    
    ret = memorySwap(memFd,memOp.m_addr,m_read,memOp.m_len,nullptr,0);
    memcpy(memOp.m_buffer,m_read,memOp.m_len);
    return ret;
}

int Hardware::plWrite(struct memoryOperation& memOp)
{
    if (!getLockStatus()) return -1;
    
    if(m_sxkInfo.m_status.m_timingMode == TIME_START) {
        RUNNING_ILLEGAL(memOp.m_addr,HARDWARE_TEST_BASEADDR+128,HARDWARE_TEST_BASEADDR+129);//参考寄存器表
        RUNNING_ILLEGAL(memOp.m_addr,HARDWARE_TEST_BASEADDR+140,HARDWARE_TEST_BASEADDR+148);//参考寄存器表
        RUNNING_ILLEGAL(memOp.m_addr,BEAM_LIST_BASEADDR,BEAM_LIST_BASEADDR+1024);//参考寄存器表
        RUNNING_ILLEGAL(memOp.m_addr,BEAM_PARAM_BASEADDR,BEAM_PARAM_BASEADDR+0x9000);//参考寄存器表
        RUNNING_ILLEGAL(memOp.m_addr,RX_AUTOALIGN_BASEADDR,RX_AUTOALIGN_BASEADDR+1024);//参考寄存器表
        RUNNING_ILLEGAL(memOp.m_addr,RX_DBF_BASEADDR,RX_DBF_BASEADDR+1024);//参考寄存器表
        RUNNING_ILLEGAL(memOp.m_addr,RX_DBF_POINT_BASEADDR,RX_DBF_POINT_BASEADDR+1024);//参考寄存器表
    }
    
    unique_lock<mutex> m_guard(m_sysRun);
    int ret = 0;
    qlog_n("写PL地址:%#x! ",memOp.m_addr);
    memcpy(m_write,memOp.m_buffer,memOp.m_len);
    ret = memorySwap(memFd,memOp.m_addr,nullptr,0,m_write,memOp.m_len);

    return ret;
}

/*** 
 * @description: 每次修改前需同步硬件寄存器
 * @return {*}
 */
void Hardware::hardwareSync()
{
    qlog_n("Sync hardware!");
    memorySwap(memFd,HARDWARE_TEST_BASEADDR,m_read,sizeof(m_sxkHardTest),nullptr,0);
    memcpy((unsigned char *)&m_sxkHardTest,m_read,sizeof(m_sxkHardTest));
}

void Hardware::setHardwareTestPara()
{
    static struct memoryOperation m_memOp;
    qlog_i("写入硬件调测寄存器 !");
    m_memOp.m_addr = HARDWARE_TEST_BASEADDR;
    m_memOp.m_len = sizeof(m_sxkHardTest);
    memcpy(m_memOp.m_buffer,(unsigned char *)&m_sxkHardTest,m_memOp.m_len );
    plWrite(m_memOp);
}

/*** 
 * @description: 校准波位设置和发射赋型使能
 * @param {int} setBeam 大于0则配置
 * @param {int} enable
 * @return {*}
 */
void Hardware::calibrationBeamMode(int setBeam,bool enable)
{
    hardwareSync();
    if (setBeam > 0) {
        m_sxkHardTest.sendbeams_set = setBeam;
    }
    if(enable) {
        m_sxkHardTest.tbf_en = 1;
    } else {
        m_sxkHardTest.tbf_en = 0;
    }
    setHardwareTestPara();
   
}

/*** 
 * @description: 改变指定波位的频点模式(bit3 - bit 0 0：频点0。1：频点1。2：频点0,1。 bit15：0，频分多波束，1 频率分集)
 * @param {int} setBeam
 * @param {int} freq
 * @return {*}
 */
void Hardware::changeBeamFreq(int setBeam,int freq)
{
    if(setBeam >= 0 && setBeam < 36) {
        struct beamConf m_beamPara;
        memcpy((uint8_t *)&m_beamPara,beamParamReg[setBeam],sizeof(struct beamConf));
        m_beamPara.m_freqMode = freq;
        memcpy(beamParamReg[setBeam],(uint8_t *)&m_beamPara,sizeof(struct beamConf));
        setBeamPara();
    }
    
}

void Hardware::setBeamListPara()
{
    if (!getLockStatus()) return;

    if(m_sxkInfo.m_status.m_timingMode == TIME_START) {
        qlog_e("The BeamList written to is write protected in radar operation.");
        return ;
    }
    unique_lock<mutex> m_guard(m_sysRun);
    qlog_i("写入波位队列表 !");
    memorySwap(memFd,BEAM_LIST_BASEADDR,(unsigned char *)readBeamList,sizeof(readBeamList),
                (unsigned char *)beamList,sizeof(beamList));
}

void Hardware::setBeamPara()
{
    if (!getLockStatus()) return;
    
    if(m_sxkInfo.m_status.m_timingMode == TIME_START) {
        qlog_e("The BeamPara written to is write protected in radar operation.");
        return ;
    }
    unique_lock<mutex> m_guard(m_sysRun);
    qlog_i("写入时序参数!");
    for (int i = 0;i<36;i++) {
        if(i < 32) {                //TODO:2025-06-06
            beamParamReg[i][0] = 1;//波位内CPI个数，默认填1
            beamParamReg[34][0] = 1;
            beamParamReg[35][0] = 1;
        }
        
        memorySwap(memFd,BEAM_PARAM_BASEADDR+0x400*i,nullptr,0,
                (unsigned char *)beamParamReg[i],sizeof(beamParamReg[i]));
    }
}

void Hardware::setDBFPara()
{
    if (!getLockStatus()) return;
    
    if(m_sxkInfo.m_status.m_timingMode == TIME_START) {
        qlog_e("雷达正在运行,接收DBF系数处于写保护中.");
        return ;
    }
    unique_lock<mutex> m_guard(m_sysRun);
    qlog_i("写入接收DBF系数 !");
    // for (int i = 0;i<512;i++)
    // {
    //     for(int j=0;j<32;j++) {
    //         m_rxDbfCoff[i].m_chlCoefIQ[j][0] = i*32+2*j;
    //         m_rxDbfCoff[i].m_chlCoefIQ[j][1] = i*32+2*j+1;
    //     }
        
    // }
    for (int i=0;i<512;i++) {
        memorySwap(memFd,RX_DBF_BASEADDR+i*sizeof(m_rxDbfCoff[i].m_chlCoefIQ),nullptr,0,
                (unsigned char *)&m_rxDbfCoff[i].m_chlCoefIQ,sizeof(m_rxDbfCoff[i].m_chlCoefIQ));
    }
}

 /*** 
  * @description: xilinx 接收DBF指向表
  * @return {*}
  */
 void Hardware::setDBFPointPara()
 {
    if (!getLockStatus()) return;

    if(m_sxkInfo.m_status.m_timingMode == TIME_START) {
        qlog_e("雷达正在运行,接收DBF系数处于写保护中.");
        return ;
    }
    unique_lock<mutex> m_guard(m_sysRun);
    qlog_i("写入接收DBF波束指向 !");

    short int rxDbfPoint[512] = { 0 };
    int k = 0;
    for (int i=0;i<32;i++) {
        for (int j=0;j<16;j++) {
            rxDbfPoint[k] = m_rxDbfPoint[i][j];
            k++;
        }
    }
    memorySwap(memFd,RX_DBF_POINT_BASEADDR,nullptr,0,
                (unsigned char *)&rxDbfPoint,sizeof(rxDbfPoint));
 }

/*** 
 * @description: 写入接收手动校准系数
 * @return {*}
 */
void Hardware::setManualCaliPara()
{
    if (!getLockStatus()) return;
    
    // if(m_sxkInfo.m_status.m_timingMode == TIME_START) {
    //     qlog_e("雷达正在运行，接收手动校准系数处于写保护中.");
    //     return ;
    // }
    uint8_t m_writeCaliCoe[512];
    memcpy(m_writeCaliCoe,(unsigned char *)m_rxManualCaliCoe,sizeof(m_rxManualCaliCoe));
    
    // for(int i=0;i<32;i++)
    // {
    //     qlog_i("m_rxManualCaliCoe[%d].m_h_i0Buffer = %x",i,m_rxManualCaliCoe[i].m_h_i0Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_h_q0Buffer = %x",i,m_rxManualCaliCoe[i].m_h_q0Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_h_i1Buffer = %x",i,m_rxManualCaliCoe[i].m_h_i1Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_h_q1Buffer = %x",i,m_rxManualCaliCoe[i].m_h_q1Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_v_i0Buffer = %x",i,m_rxManualCaliCoe[i].m_v_i0Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_v_q0Buffer = %x",i,m_rxManualCaliCoe[i].m_v_q0Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_v_i1Buffer = %x",i,m_rxManualCaliCoe[i].m_v_i1Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_v_q1Buffer = %x",i,m_rxManualCaliCoe[i].m_v_q1Buffer);
    // }
    
    unique_lock<mutex> m_guard(m_sysRun);
    qlog_i("写入接收手动校准系数 !");
    memorySwap(memFd,RX_MANUALALIGN_BASEADDR,nullptr,0,
                m_writeCaliCoe,sizeof(m_writeCaliCoe));
}

 /*** 
  * @description: 写入接收自动校准系数
  * @return {*}
  */
void Hardware::setAutoCaliPara()
{
    if (!getLockStatus()) return;

    // if(m_sxkInfo.m_status.m_timingMode == TIME_START) {
    //     qlog_e("雷达正在运行，接收自动校准系数处于写保护中.");
    //     return ;
    // }
    uint8_t m_writeCaliCoe[512];
    memcpy(m_writeCaliCoe,(unsigned char *)m_rxAutoCaliCoe,sizeof(m_rxAutoCaliCoe));
    // for(int i=0;i<32;i++)
    // {
    //     qlog_i("m_rxManualCaliCoe[%d].m_h_i0Buffer = %x",i,m_rxManualCaliCoe[i].m_h_i0Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_h_q0Buffer = %x",i,m_rxManualCaliCoe[i].m_h_q0Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_h_i1Buffer = %x",i,m_rxManualCaliCoe[i].m_h_i1Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_h_q1Buffer = %x",i,m_rxManualCaliCoe[i].m_h_q1Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_v_i0Buffer = %x",i,m_rxManualCaliCoe[i].m_v_i0Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_v_q0Buffer = %x",i,m_rxManualCaliCoe[i].m_v_q0Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_v_i1Buffer = %x",i,m_rxManualCaliCoe[i].m_v_i1Buffer);
    //     qlog_i("m_rxManualCaliCoe[%d].m_v_q1Buffer = %x",i,m_rxManualCaliCoe[i].m_v_q1Buffer);
    // }
    unique_lock<mutex> m_guard(m_sysRun);
    qlog_i("写入接收自动校准系数 !");
    memorySwap(memFd,RX_AUTOALIGN_BASEADDR,nullptr,0,
                m_writeCaliCoe,sizeof(m_writeCaliCoe));
}

/**
 * @brief: 设置系统启动参数
 * @return {*}
 */
void Hardware::setSysTimingPara()
{
    if (!getLockStatus()) return;
    
     //写入control reg map寄存器
    qlog_n("writer timing generator");
    unique_lock<mutex> m_guard(m_sysRun);
    switch(m_controlReg.m_timingStatus)
    {
        case TIME_START:qlog_i("开启时序..");
        break;
        case TIME_H_SEND_CALL:qlog_i("设置H极化发射校准..");
        break;
        case TIME_V_SEND_CALL:qlog_i("设置V极化发射校准..");
        break;
        case TIME_H_REVICE_CALL:qlog_i("设置H极化接收校准..");
        break;
        case TIME_V_REVICE_CALL:qlog_i("设置V极化接收校准..");
        break;
        case TIME_STOP:qlog_i("停止时序..");
        break;
    }
    m_sxkInfo.m_status.m_timingMode = m_controlReg.m_timingStatus;
    //3.系统参数配置协议中的波束模式选择请写入到内存模型Control Reg Map部分的信处波束模式设置
    //4.系统参数配置协议中的有效波位数量请写入到内存模型Control Reg Map部分的设置扫描波位数部分
    //5.当解系统参数配置协议后请将Control Reg Map参数就绪部分置1，否则该部分应该置0
    m_controlReg.m_paramReady = 1;
    m_controlReg.m_timingStatus = TIME_STOP;//参数未就绪
    memorySwap(memFd,TIMING_CONFIG_BASEADDR,nullptr,0,(unsigned char *)&m_controlReg,16);
    /*6.写入Control Reg Map
    *01：产生正常时序；
    *02：H极化发射校准；
    *03：V极化发射校准；
    *04：H极化接收校准；
    *05：V极化接收校准；
    *06：停止
    */
    if (m_sxkInfo.m_status.m_timingMode != TIME_STOP) {
        m_controlReg.m_paramReady = 1;
        m_controlReg.m_timingStatus = m_sxkInfo.m_status.m_timingMode;//参数就绪
        memorySwap(memFd,TIMING_CONFIG_BASEADDR,nullptr,0,(unsigned char *)&m_controlReg,16);
        if(m_controlReg.m_timingStatus != TIME_START) {
            m_controlReg.m_timingStatus = TIME_STOP;//触发完成后恢复出厂设置，防止多次写入校准标志
        }
            
    }
}

void Hardware::setPhaseCodePara()
{
    qlog_i("写入相位编码参数,写入:%d条.",m_phaseWriteNum);
    
    unsigned long addr = BEAM_PHASECODE_BASEADDR;
    uint16_t m_buff[128] = {0};
    memset(m_buff,0,sizeof(m_buff));
    memcpy(m_buff,m_phaseCode,sizeof(m_phaseCode));
    // for(int j=0; j<32; j++) {
    //     qlog_i("phaseCode:m_buff[%d]=%d",j,m_buff[j]);
    //     qlog_i("phaseCode:m_buff[%d]=%d",j+32,m_buff[j+32]);
    //     qlog_i("phaseCode:m_buff[%d]=%d",j+64,m_buff[j+64]);
    //     qlog_i("phaseCode:m_buff[%d]=%d",j+96,m_buff[j+96]);
    // }
    for(int i = 0;i< m_phaseWriteNum;i++) {
        addr = addr + sizeof(m_phaseCode) * i;
        memorySwap(memFd,addr,nullptr,0,(unsigned char *)m_buff,sizeof(m_buff));
    } 
}

void Hardware::servoProtocolTask(Hardware *args)
{
#define WAIT_PROTOCOL_DATA_ENTITY_TIMEOUT 10
#define SERVO_HEADER	0xFBFA
#define SERVO_STATUS_LENGTH	40
#define STATUS_CMD  03    
	static uint8_t getCmdHeadBuff[2] = {0};
    static uint8_t getDataTempBuff[SERVO_STATUS_LENGTH];
	while(args->isRunning)
	{
        if (sysRunStatus == SYS_INIT) {
			qlog_d("伺服解析线程暂停运行...");
            std::this_thread::sleep_for(std::chrono::milliseconds(600));
            continue;
		}
        if(args->m_mtUart->dataIsValid())
        {
            getCmdHeadBuff[0] = getCmdHeadBuff[1];
		    getCmdHeadBuff[1] = 0;
            getCmdHeadBuff[1] = args->m_mtUart->take();
            uint16_t *getHeadValue = (uint16_t *)getCmdHeadBuff;
            if(SERVO_HEADER == *getHeadValue) //头正确
            {
                int waitDataTimeCount=0;
			    memcpy(getDataTempBuff,getCmdHeadBuff,sizeof(getCmdHeadBuff));
                while(args->m_mtUart->dataSize() < (int64_t)(SERVO_STATUS_LENGTH-2))
                {
                    std::this_thread::sleep_for(std::chrono::milliseconds(10));
                    waitDataTimeCount ++;
                    if(waitDataTimeCount > WAIT_PROTOCOL_DATA_ENTITY_TIMEOUT)
                    {
                        waitDataTimeCount = 0;
                        qlog_e("servo_uart revice date timeout");
                        break;
                    }
                }
                args->m_mtUart->recvfrom((getDataTempBuff+sizeof(getCmdHeadBuff)),(SERVO_STATUS_LENGTH-2));
                uint16_t iCrc = args->m_servo->getModbusCRC16(getDataTempBuff,SERVO_STATUS_LENGTH-2);
                // qlog_i("servo crc:%#x.",iCrc);
                if( (iCrc == *(uint16_t *)(getDataTempBuff+SERVO_STATUS_LENGTH-2)) && getDataTempBuff[2] == STATUS_CMD)
                {	
                    // qlog_i("servo crc right");
                    // qlog_hexdump("servo",16,getDataTempBuff,SERVO_STATUS_LENGTH);
                    memcpy((uint8_t *)&args->m_servo->H_ConfigServo.m_status,&getDataTempBuff[3],sizeof(args->m_servo->H_ConfigServo.m_status));
                    std::this_thread::sleep_for(std::chrono::milliseconds(20));
			    }
            }
        } else {
            // args->m_servo->servoPackage_b4();
            // std::this_thread::sleep_for(std::chrono::milliseconds(300));
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
        }
        
    }
}


/*** 
 * @description: 获取1000ms数据（温度）
 * @return {*}
 */
void Hardware::process_1000ms()
{
    if (m_process1000ms >= PROCESS_1S) {
        m_sxkInfo.m_temperature.m_plTemp = plTemperature();
        m_sxkInfo.m_temperature.m_psTemp = psTemperature();
        getSht3xData(&m_sxkInfo.m_temperature.m_sensorTemp,&m_sxkInfo.m_temperature.m_sensorHumidity);
        m_process1000ms = 0;
    } else {
        m_process1000ms++;
    }
}

/*** 
 * @description: 获取1500ms数据（电压电流）
 * @return {*}
 */
void Hardware::process_1500ms()
{
    if (m_process1500ms >= PROCESS_1R5S) {
        hwHandle(m_sxkInfo.m_sxkParam);
        m_process1500ms = 0;
    } else {
        m_process1500ms++;
    }
}

/*** 
 * @description: 获取2000ms数据（7044和5341）
 * @return {*}
 */
void Hardware::process_2000ms()
{
    if (m_process2000ms >= PROCESS_2S) {
        hmc7044GetStatus(m_sxkInfo.m_hmc7044);
        si5341GetStatus(m_sxkInfo.m_si5341);
        m_process2000ms = 0;
    } else {
        m_process2000ms++;
    }
}

/*** 
 * @description: 获取3000ms数据（GNSS）
 * @return {*}
 */
void Hardware::process_3000ms()
{
    if (m_process3000ms >= PROCESS_3S) {
        memcpy(&m_sxkInfo.m_gpsStatus,m_gnssUart->Get(),sizeof(m_sxkInfo.m_gpsStatus));//获取GNSS数据
        
        m_process3000ms = 0;
    } else {
        m_process3000ms++;
    }
}

/*** 
 * @description: 获取5000ms数据（QSFP）
 * @return {*}
 */
void Hardware::process_5000ms()
{
    if (m_process5000ms >= PROCESS_5S) {
        qsfpGetStatus(m_sxkInfo.m_qsfpUpdate);
        m_process5000ms = 0;
    } else {
        m_process5000ms++;
    }
}


bool Hardware::resetInit(int rst)
{
    bool rets = true;
    int m_lmxLock = 0,m_hmc7044Lock = 0;
    m_hmc7044Lock = hmc7044GetLock();
    m_lmxLock = lmx2820GetLock();
    qlog_w("复位执行：%d.",rst);
    if ( rst == m_all) {
        if (m_hmc7044Lock != 1) {
            qlog_w("重新复位HMC7044设备..");
            hmc7044Reset();
            sleep(5);
        }
        if(m_lmxLock != 2) {
            qlog_w("重新复位lmx2820设备..");
            if ( lmx2820Reset() ) {
                lmx2820Config();
                sleep(5);
            } else {
                rets = false;
            }
        }
        m_hmc7044Lock = hmc7044GetLock();
        m_lmxLock = lmx2820GetLock();
        if( m_hmc7044Lock == 1 && m_lmxLock == 2 ) { //重新配置9171
            qlog_w("重新配置9171");
            plReset();//TODO：2025-1-22新增
            initPlRfSync();
            ad9171Config();

            dataInit();
            setBeamPara();
            setBeamListPara();
            setDBFPara();
        } else {
            qlog_w("此次复位后LMX2820:%s,HMC7044:%s",
            (m_lmxLock == 2)?"锁定":"未锁定",
            (m_hmc7044Lock == 1)?"锁定":"未锁定");
        }
        
    }
    else if ( rst == m_hmc7044 ) {
        if (m_hmc7044Lock != 1) {
        qlog_w("重新复位HMC7044设备..");
        hmc7044Reset();
        sleep(5);
        } else {
            qlog_w("HMC7044已锁定.不需要初始化");
        }
        hmc7044GetStatus(m_sxkInfo.m_hmc7044);
    }
    else if ( rst == m_lmx2820 ) {
        if(m_lmxLock != 2) {
        qlog_w("重新复位lmx2820设备..");
        if ( lmx2820Reset() ) {
            lmx2820Config();
            sleep(5);
        } else {
            rets = false;
        }
        } else {
            qlog_w("LMX2820已锁定.不需要初始化");
        }
    }
    else if ( rst == m_ad9171 ) {
            if( m_hmc7044Lock == 1 && m_lmxLock == 2 ) { //重新配置9171
            ad9171Config();
            } else {
                qlog_w("复位后LMX2820:%s,HMC7044:%s",
                (m_lmxLock == 2)?"锁定":"未锁定",
                (m_hmc7044Lock == 1)?"锁定":"未锁定");
            }
    }
    else if ( rst == m_timingParam)  {
        qlog_w("重新初始化时序参数.."); 
        setBeamPara();
    }
    else if ( rst == m_dbf ) {
        qlog_w("重新初始化DBF参数..");
        dataInit();
        setDBFPara();
    }
    else if( rst == m_beamList ){
        qlog_w("重新初始化波位队列表..");
        dataInit();
        setBeamListPara();
    } else {
        qlog_e("复位初始化指令错误=%d,有效(0-6).",rst);
        return rets;
    }
    return rets;
            
}

void Hardware::sxkConverLx()
{
    //时序卡参数重新排列
    memcpy(&m_radarSystemInfo.sxkpara.cvParam,&m_sxkInfo.m_sxkParam,sizeof(struct cvSXParam_r));
    memcpy(&m_radarSystemInfo.sxkpara.hmc7044,&m_sxkInfo.m_hmc7044,sizeof(struct hmc7044_r));
    memcpy(&m_radarSystemInfo.sxkpara.lvdsStatus,&m_sxkInfo.m_lvdsError,sizeof(struct sxkLvdsError_r));
    memcpy(&m_radarSystemInfo.sxkpara.plVerisonInfo,&m_sxkInfo.m_plVersion,sizeof(struct plVerisonInfo_r));
    memcpy(&m_radarSystemInfo.sxkpara.psVerisonInfo,&m_sxkInfo.m_psVersion,sizeof(struct psVerisonInfo_r));
    memcpy(&m_radarSystemInfo.sxkpara.si5341,&m_sxkInfo.m_si5341,sizeof(struct si5341_r));
    memcpy(&m_radarSystemInfo.sxkpara.subSt,&m_sxkInfo.m_status,sizeof(struct subSXStatus_r));
    memcpy(&m_radarSystemInfo.sxkpara.tempParam,&m_sxkInfo.m_temperature,sizeof(struct sxkTemperature_r));
    gnssModbusRtu::Instance().getData(&m_sxkInfo.m_gnssUpdateRtu);
    memcpy(&m_radarSystemInfo.sxkpara.gnssUpdate,&m_sxkInfo.m_gnssUpdateRtu,sizeof(struct gnssUpdateRtu));//TODO:2025-9-27

    // int a = sizeof(m_radarSystemInfo.sxkpara);//411
    // a = sizeof(m_radarSystemInfo.sxkpara.gnssUpdate);//146
    // a= sizeof(m_radarSystemInfo);//1463
    // a = sizeof(m_radarSystemInfo.trpara);//638
    // a = sizeof(m_radarSystemInfo.adpara);//284
    // a= sizeof(m_radarSystemInfo.pzpara);//130
}


// void Hardware::getIniControlReg(const char *path)
// {
//     int flags = 0;
//     m_sxkHardTest.az_start = readIntValue("ControlBeam","az_start",path);
//     m_sxkHardTest.az_end = readIntValue("ControlBeam","az_end",path);
//     m_sxkHardTest.servo_speed = readIntValue("ControlBeam","servo_speed",path);
//     m_sxkHardTest.servo_switch = readIntValue("ControlBeam","servo_switch",path);
//     m_sxkHardTest.az_switch = readIntValue("ControlBeam","az_switch",path);
//     m_sxkHardTest.fm_amp = readIntValue("ControlBeam","fm_amp",path);
//     m_sxkHardTest.am_amp = readIntValue("ControlBeam","am_amp",path);
//     m_sxkHardTest.prt0_delay = readIntValue("ControlBeam","prt0_delay",path);
//     m_sxkHardTest.prt1_delay = readIntValue("ControlBeam","prt1_delay",path);
//     m_sxkHardTest.enparam = readIntValue("ControlBeam","enparam",path);
//     m_sxkHardTest.ensenddelay = readIntValue("ControlBeam","ensenddelay",path);
//     m_sxkHardTest.en_encoding = readIntValue("ControlBeam","en_encoding",path);
//     m_sxkHardTest.radiate_switch = readIntValue("ControlBeam","radiate_switch",path);
//     m_sxkHardTest.test_enable = readIntValue("ControlBeam","test_enable",path);
//     m_sxkHardTest.test_mode = readIntValue("ControlBeam","test_mode",path);
//     m_sxkHardTest.interrput_enable = readIntValue("ControlBeam","interrput_enable",path);
//     m_sxkHardTest.dac_sidelobe = readIntValue("ControlBeam","dac_sidelobe",path);
//     m_sxkHardTest.dac_fm_strength = readIntValue("ControlBeam","dac_fm_strength",path);
//     m_sxkHardTest.dac_am_strength = readIntValue("ControlBeam","dac_am_strength",path);
//     m_sxkHardTest.initial_phase = readIntValue("ControlBeam","initial_phase",path);
//     m_sxkHardTest.dac_source = readIntValue("ControlBeam","dac_source",path);
//     m_sxkHardTest.minfreq_0 = readIntValue("ControlBeam","minfreq_0",path);
//     m_sxkHardTest.minfreq_1 = readIntValue("ControlBeam","minfreq_1",path);
//     m_sxkHardTest.WaveWidth = readIntValue("ControlBeam","WaveWidth",path);
//     m_sxkHardTest.internal_cnt_hold = readIntValue("ControlBeam","internal_cnt_hold",path);
//     m_sxkHardTest.midfreq_attenuator0 = readIntValue("ControlBeam","midfreq_attenuator0",path);
//     m_sxkHardTest.midfreq_attenuator1 = readIntValue("ControlBeam","midfreq_attenuator1",path);
//     m_sxkHardTest.tbf_en = readIntValue("ControlBeam","tbf_en",path);
//     m_sxkHardTest.sendbeams_set = readIntValue("ControlBeam","sendbeams_set",path);
//     m_sxkHardTest.dma_selected = readIntValue("ControlBeam","dma_selected",path);
//     flags = readIntValue("ControlBeam","ControlBeamFlag",path);
//     qlog_i("hard test init : %d",flags);
//     // flags > 0?ControlBeamFlag =true:ControlBeamFlag=false;
// }

